<?php
namespace Modules\Payment\Entities;

use \EasyWeChat;
use Modules\Payment\Entities\PaymentRecord;

use ThrowException;
use Miniapp;
use Cache;

// 此处使用easy wechat的包实现
class EasyWechatPay
{
	protected $clientName;
	protected $payType;
	protected $pay;

	public function __construct($clientName = 'default', $payType = 'miniapp')
	{
		$config = config('wechat.payment')['default'];

		// if ($clientName)
		// 	$key = $clientName . '_' . $payType;
		// else 
		// 	$key = array_keys($config)[0];

		// $config = $config[];
		$this->pay = EasyWeChat::payment($clientName);

		$this->payType = $payType;
		$this->clientName = $clientName;
	}

	public function __call($name, $arguments)
    {
    	return call_user_func_array(array($this->pay, $name), $arguments);
    }

	public function payToUser($user, $money, $options)
	{
		$number = @$options['number'];
		$openid = $user->getOpenid('miniapp', $this->clientName);
		$desc = $options['desc'];

		$res = $this->pay->transfer->toBalance([
		    'partner_trade_no' => $number, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
		    'openid' => $openid,
		    'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
		    // 're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
		    'amount' => $money, // 企业付款金额，单位为分
		    'desc' => $desc, // 企业付款操作说明信息。必填
		]);

		if (@$res['return_code'] !== 'SUCCESS') {
			\Log::error('企业付款到零钱失败 ' . @$res['return_msg']);
			ThrowException::Conflict(@$res['return_msg']);
		}

		if (@$res['result_code'] !== 'SUCCESS') {
			\Log::error('企业付款到零钱失败 ' . @$res['err_code_des']);
			ThrowException::Conflict(@$res['err_code_des']);
		}

		return $res;
	}
}
